package com.example.demo.controller;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.pojo.Cinema;
import com.example.demo.service.DataStatisticsService;
import com.example.demo.service.MovieService;
import com.example.demo.service.imp.MovieServiceImp;
import com.woniuxy.movice.entity.Movie;
import com.example.demo.pojo.Round;
import com.example.demo.pojo.Round2;
import com.example.demo.service.DataStatisticsService;
import com.example.demo.service.imp.MovieServiceImp;
import com.woniuxy.movice.entity.MovieHall;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@Api("影片操作")
@RestController
@RequestMapping("/movie")
public class MovieController {
	String newFileName="";
	
	@Resource
	MovieServiceImp movieServiceImp;
	
	@Resource
	private MovieService movieService;

	public MovieServiceImp getMovieServiceImp() {
		return movieServiceImp;
	}

	public void setMovieServiceImp(MovieServiceImp movieServiceImp) {
		this.movieServiceImp = movieServiceImp;
	}
	
	@ApiOperation(value="添加影厅",notes="yid=4，ytname=Metal厅，ytlayout= [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"
			+ "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"
			+ "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1],"
			+ "[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]"
			+ "返回是否成功")
	@PostMapping("/hall")
	public String addHall(MovieHall hall) {  
		String result = "添加失败";
		//查名字重复
		int count = movieServiceImp.sameName(hall);
		if(count>0) {
			result = "影厅名重复！";
		}else {
			movieServiceImp.addHall(hall);
			result = "添加成功！";
		}
		return result;
	}

	@ApiOperation(value="影片封面上传",notes="封面地址")
	@RequestMapping("/add")
	@ResponseBody
	public Object handleFileUpload(HttpServletRequest request) {
	    MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
	    List<MultipartFile> files = (params.getFiles("file"));
		//接收前端传过来的字段
	    //String name = params.getParameter("name");
	    //System.out.println(re);
	    MultipartFile file = null;
	    //先设置一个数组来装file路径
	    List imgs = new ArrayList();
	   //设置图片路径
		String UPLOAD_FOLDER = "target/classes/static/movies/";
	    for (int i = 0; i < files.size(); ++i) {
	        file = files.get(i);
	        if (!file.isEmpty()) {
	            try {
	                byte[] bytes = file.getBytes();
	                // 获取图片的文件名
	                String fileName = file.getOriginalFilename();
	                // 获取图片的扩展名
	                String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
	                //产生随机随
	                int rand=(int)(1+Math.random()*(100-1+1));
	                // 新的图片文件名 = 获取时间戳+随机数"."图片扩展名
	                 newFileName = String.valueOf(System.currentTimeMillis()) +rand+ "." + extensionName;
	                //图片路径
	                Path path = Paths.get(UPLOAD_FOLDER + newFileName);
					System.out.println("lj: " + path);
	                imgs.add(path);
	                //String dbpath="upload/"+newFileName;
	                //如果没有files文件夹，则创建
	                if (!Files.isWritable(path)) {
	                    Files.createDirectories(Paths.get(UPLOAD_FOLDER));
	                }
	                //文件写入指定路径
	                Files.write(path, bytes);
	            } catch (Exception e) {
	                return "图片上传失败 " + i + " => " + e.getMessage();
	            }
	        } else {
	            return "图片上传失败 " + i + " because the file was empty.";
	        }
	    }
	    Map<String,Object> map=new HashMap<>();
	    map.put("code",0);
	    map.put("msg","");
	    map.put("data","newFileName");
	    return map;
	}
	
	@ApiOperation(value="根据影院查找影厅",notes="yid=4,返回影厅集合")
	@GetMapping("/hall/{yid}")
	public ArrayList<MovieHall> showHall(@PathVariable int yid){
		ArrayList<MovieHall> halls = new ArrayList<MovieHall>();
		halls = movieServiceImp.allHall(yid);
		return halls;
	}
	
	@ApiOperation(value="删除影厅",notes="ytid=4")
	@DeleteMapping("/hall/{ytid}")
	public String deleteHall(@PathVariable int ytid){
		String result = "删除失败";
		//检查该影厅是否还有排片
		int i = movieService.roundByYt(ytid);
		if(i>0) {
			result="该厅还有排片，无法删除";
		}else {
			movieService.deleHall(ytid);
			result="删除成功";
		}
		
		return result;
	}
	
	@ApiOperation(value="显示所有影院",notes="返回影院集合")
	@GetMapping("/cinema")
	public ArrayList<Cinema> showCinema() {
		ArrayList<Cinema> cinemas = new ArrayList<Cinema>();
		cinemas = movieServiceImp.allCinema();
		return cinemas;
	}
	@ApiOperation(value="显示影院的所有电影",notes="返回电影集合")
	@GetMapping("/movies")
	public ArrayList<com.example.demo.pojo.Movie> showMovie() {
		ArrayList<com.example.demo.pojo.Movie> movies = new ArrayList<com.example.demo.pojo.Movie>();
		movies = movieServiceImp.allMovie();
		return movies;
	}
	@ApiOperation(value="根据日期和影厅查找排片信息",notes="vstart=2019-09-18，yid=1，ytid=1 返回排片集合")
	@PostMapping("/arrange/search")
	public ArrayList<Round> showArranges(String vstart,int yid,int ytid) {
		ArrayList<Round> arranges = new ArrayList<Round>();
		arranges = movieServiceImp.showArranges(vstart,yid,ytid);
		System.out.println(arranges);
		return arranges;
	}
	@ApiOperation(value="添加排片",notes="mid:1,yid:4,pstart:起始时间,pend:结束时间,pprice:30,ytid:1")
	@PostMapping("/arrange")
	public String addArrange(Round2 round) {
		String result = "添加失败";
		//将月份-1
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(round.getPstart());
		c2.setTime(round.getPend());
		c1.add(Calendar.MONTH, -1);
		c2.add(Calendar.MONTH, -1);
		round.setPstart(c1.getTime());
		round.setPend(c2.getTime());
		
		//根据ytid查找对应的布局
		round.setYtlayout(movieServiceImp.findLayout(round.getYtid()));
		//验证排片时间没有冲突
		int i = movieServiceImp.interTime(round.getPstart(),round.getPend());
		if(i>0) {
			result="时间冲突 请重新选择！";
		}else {
			movieServiceImp.addArrange(round);
			result="添加成功";
		}
		return result;
	}
	@ApiOperation(value="删除排片")
	@DeleteMapping("/arrange/{id}")
	public String addArrange(@PathVariable int id) {
		System.out.println(id);
		String result = "删除失败！";
		//验证该场次是否没有卖出票
		int i = movieServiceImp.findOrderCount(id);
		if(i>0) {
			result="该场次已售票，无法删除";
		}else {
			//删除
			movieServiceImp.deleArrange(id);
			result="删除成功！";
		}
		return result;
	}

	@RequestMapping("/upload")
	@ResponseBody
	public String uploadmovie(String a,String b,String c,String d,
			String e,String f,String g,String h,
			String username,String actor,String desc,String country,
			Integer time,String language,String mstar) {
		//多选框字符拼接
		StringBuffer sb=new StringBuffer();
		if(a!=null) {
			sb.append(a+",");
		}
		if(b!=null) {
			sb.append(b+",");
		}
		if(c!=null) {
			sb.append(c+",");
		}
		if(d!=null) {
			sb.append(d+",");
		}
		if(e!=null) {
			sb.append(e+",");
		}
		if(g!=null) {
			sb.append(g+",");
		}
		if(h!=null) {
			sb.append(h+",");
		}
		//封装影片所有信息
		Movie movie=new Movie();
		movie.setMname(username);
		movie.setRef("movies/"+newFileName);
		movie.setLanguage(language);
		movie.setMtype(sb.toString());
		movie.setLocation(country);
		movie.setDirector(actor);
		movie.setMlength(time);
		movie.setMmassage(desc);
		movie.setMstar(mstar);
		movieService.addMovie(movie);
		return "添加成功";
	}

}